"""

与用户相关的视图函数

"""
from flask import g, render_template, redirect, request, jsonify, current_app, session
from werkzeug.security import generate_password_hash

from info import db, constants
from info.constants import QINIU_DOMIN_PREFIX
from info.models import User, News, Category
from info.utils.image_storage import storage
from info.utils.response_code import RET
from . import userblu
from info.utils.common import user_data_session


# 默认用户的路由
@userblu.route('/')
@user_data_session
def user():
    # 获取当前用户的状态
    user = g.user

    if not user:
        return redirect("/")

    return render_template("user/user.html", user=user)


# 用户修改资料的路由
@userblu.route("/base_info", methods=["POST", "GET"])
@user_data_session
def base_info():
    # 获取当前用户的状态
    user = g.user

    if not user:
        return redirect("/")

    # 根据方法进行判断
    if request.method == "GET":
        return render_template("user/user_base_info.html", user=user)

    # 下面是接收POST请求的时候，给浏览器返回json内容
    base_info_param = request.json

    signature = base_info_param.get("signature")
    nick_name = base_info_param.get("nick_name")
    gender = base_info_param.get("gender")

    if not all([signature, nick_name, gender]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数传入错误")

    if gender not in (['MAN', 'WOMAN']):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    # 保存数据
    user.nick_name = nick_name
    user.gender = gender
    user.signature = signature

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存数据失败")

    # 将 session 中保存的数据进行实时更新 更新一下session信息
    session["nick_name"] = nick_name

    # 返回结果给前端
    return jsonify(errno=RET.OK, errmsg="修改成功")


# 用户修改头像的路由
@userblu.route("/avatar_setting", methods=["POST", "GET"])
@user_data_session
def avatar_setting():
    # 获取当前用户的状态
    user = g.user

    if not user:
        return redirect("/")

    if request.method == "GET":
        return render_template('user/user_pic_info.html', user=user)

    # 1. 获取到上传的文件
    try:
        # 获取用户上传的图片
        avatar_file = request.files.get("avatar").read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="读取文件出错")

    # 2. 再将文件上传到七牛云
    try:
        url = storage(avatar_file)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="上传图片错误")

    # 3. 将头像信息更新到当前用户的模型中

    # 设置用户模型相关数据
    user.avatar_url = QINIU_DOMIN_PREFIX + url
    # 将数据保存到数据库
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存用户数据错误")

    # 4. 返回上传的结果<avatar_url>
    return jsonify(errno=RET.OK, errmsg="OK", avatar_url=user.avatar_url)


# 用户关注的路由
@userblu.route("/user_follow")
@user_data_session
def user_follow():
    # 获取当前用户的状态
    user = g.user

    if not user:
        return redirect("/")

    return render_template("user/user_follow.html", user=user)


# 密码修改 change_password
@userblu.route("/change_password", methods=["POST", "GET"])
@user_data_session
def change_password():
    # 获取当前用户的状态
    user = g.user

    if not user:
        return redirect("/")

    if request.method == "GET":
        return render_template("user/user_pass_info.html", user=user)

    # 当请求方法是POST的时候，处理数据
    # 1 获取参数
    change_password_params = request.json

    old_password = change_password_params.get("old_password")

    new_password = change_password_params.get("new_password")

    # 2 验证参数
    if not all([old_password, new_password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不足")

    # 3 处理数据
    # 验证第一次输入的密码是否跟数据库保存的密码一致

    if not user.check_passowrd(old_password):
        return jsonify(errno=RET.PWDERR, errmsg="密码错误")

    # 第一次输入的密码跟当前密码相同的话，那么就开始修改
    user.password_hash = generate_password_hash(new_password)

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.debug(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="修改密码失败")

    return jsonify(errno=RET.OK, errmsg="修改密码成功")


# 用户收藏 user_collection
@userblu.route("/user_collection", methods=["POST", "GET"])
@user_data_session
def user_collection():
    # 获取当前用户的状态
    user = g.user

    if not user:
        return redirect("/")

    """
    需求：
        使用分页的形式展示用户所收藏的新闻
        可以使用 url 的查询字符串传入不同的页数进行模板渲染不同的数据
        可以支付使用模板显示，也可以使用 ajax 进行请求    
    """
    # 查询该用户收藏的所有的新闻
    # 获取页数
    p = request.args.get("p", 1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1

    collections = []
    current_page = 1
    total_page = 1
    try:
        # 进行分页数据查询
        paginate = user.collection_news.paginate(p, constants.USER_COLLECTION_MAX_NEWS, False)
        # 获取分页数据
        collections = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    # 收藏列表
    collection_dict_li = []
    for news in collections:
        collection_dict_li.append(news.to_basic_dict())

    data = {"total_page": total_page, "current_page": current_page, "collections": collection_dict_li}

    return render_template("user/user_collection.html", user=user, data=data)


# 用户新闻发布 new_publish
@userblu.route("/new_publish", methods=["POST", "GET"])
@user_data_session
def new_publish():
    # 获取当前用户的状态
    user = g.user

    if not user:
        return redirect("/")

    if request.method == "GET":
        # 获取分类信息
        category_list = []
        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.debug(e)
            return jsonify(errno=RET.DBERR, errmsg="查询分类信息失败")
        for c in categories:
            category_list.append(c.to_dict())

        return render_template("user/user_news_release.html", user=user, category_list=category_list)

    # 接收POST请求的时候
    # 1. 获取要提交的数据
    title = request.form.get("title")
    source = "个人发布"
    digest = request.form.get("digest")
    content = request.form.get("content")
    index_image = request.files.get("index_image")
    category_id = int(request.form.get("category_id"))
    # 1.1 判断数据是否有值
    if not all([title, source, digest, content, index_image, category_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    # 1.2 尝试读取图片
    try:
        index_image = index_image.read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    # 2. 将标题图片上传到七牛
    try:
        key = storage(index_image)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="上传图片错误")

    # 3. 初始化新闻模型，并设置相关数据
    news = News()
    news.title = title
    news.digest = digest
    news.source = source
    news.content = content
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + key
    news.category_id = category_id
    news.user_id = user.id
    # 1代表待审核状态
    news.status = 1
    # 新版本的MySQL5.X不能不填值
    news.reason = 0

    # 4. 保存到数据库
    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        print("======================")
        print(e)
        print("======================")
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存数据失败")
    # 5. 返回结果
    return jsonify(errno=RET.OK, errmsg="发布成功，等待审核")


# 新闻列表 new_list
@userblu.route("/new_list")
@user_data_session
def new_list():
    # 获取当前用户的状态
    user = g.user

    if not user:
        return redirect("/")

    # 获取页数
    p = request.args.get("p", 1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1

    user = g.user
    news_li = []
    current_page = 1
    total_page = 1
    try:
        paginate = News.query.filter(News.user_id == user.id).paginate(p, constants.USER_COLLECTION_MAX_NEWS, False)
        # 获取当前页数据
        news_li = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    news_dict_li = []

    for news_item in news_li:
        news_dict_li.append(news_item.to_review_dict())
    data = {"news_list": news_dict_li, "total_page": total_page, "current_page": current_page}

    return render_template('user/user_news_list.html', data=data)
